<template>
  <div
    class="search-div"
    :style="{
      background: styleSwitch.searchBack ? 'rgba(233, 89, 60, 1)' : '#ffffff',
    }"
  >
    <van-search
      autofocus
      show-action
      placeholder="搜索游记/地点等"
      @focus="focusInput"
      @update:model-value="updateInput"
      v-model="keywords"
      @clear="clearEvent"
      @search="onSearch"
      background="none"
    >
      <template #action>
        <div
          @click="onSearch"
          :style="{ color: styleSwitch.hotCityExist ? '#ffffff' : '#151419' }"
        >
          搜索
        </div>
      </template>
    </van-search>
    <!-- 分类搜索 -->
    <van-tabs
      v-if="styleSwitch.categorySearch"
      v-model:active="active"
      background="none"
      :color="styleSwitch.hotCityExist ? '#f9cd15' : '#171520'"
      :title-inactive-color="styleSwitch.hotCityExist ? '#f1ad9b' : '#727272'"
      :title-active-color="styleSwitch.hotCityExist ? '#fceeeb' : '#171520'"
      @click-tab="onClickTab"
    >
      <van-tab title="游记"></van-tab>
      <van-tab title="作者"></van-tab>
    </van-tabs>
  </div>
  <!-- 占位高度 -->
  <div
    :class="[
      styleSwitch.categorySearch ? 'search_height_y' : 'search_height_n',
    ]"
  ></div>
  <!-- 搜索历史和热门城市 v-show="historyShow"-->
  <div class="search-padding" v-show="historyShow">
    <div v-if="historyData.length > 0">
      <div
        class="search-history global-display global-a-items global-j-content"
      >
        <p>历史搜索</p>
        <img
          src="@/icon/search/delete-search.png"
          alt=""
          @click="deleteHistory"
        />
      </div>
      <div class="history-data global-display global-a-items global-f-wrap">
        <p
          v-for="(item, index) in historyData"
          :key="index"
          @click="goSearch(item)"
        >
          {{ item }}
        </p>
      </div>
    </div>
    <!-- 热门城市 -->
    <div class="search-history global-display global-a-items global-j-content">
      <p>热门旅游城市</p>
    </div>
    <div
      class="Hot-city global-display global-a-items fadeIn"
      v-for="(item, index) in hotCity"
      :key="index"
      @click="goSearch(item._id)"
    >
      <img :src="item.image" alt="" />
      <div>
        <p>{{ item._id }}</p>
        <p>{{ item.count }}人去过</p>
      </div>
    </div>
  </div>
  <!-- 显示实时搜索列表 -->
  <div class="search-list" v-show="listShow">
    <p
      class="text-show"
      v-for="(item, index) in searchList"
      :key="index"
      @click="goSearch(item)"
    >
      {{ item }}
    </p>
  </div>
  <!-- 如果有热门城市返回 -->
  <div v-if="styleSwitch.hotCityExist">
    <hotCityView
      :hotCity_Data="hotCity_Data"
      :hotCityTravels="hotCityTravels"
      :swiperWidthPx="swiperWidthPx"
    />
  </div>
  <!-- 展示搜索的作者 -->
  <div v-if="styleSwitch.author">
    <van-list
      v-model:loading="loadingAuth"
      :finished="finishedAuth"
      finished-text="没有更多了"
      :immediate-check="false"
      offset="100"
      @load="onLoadAuth"
    >
      <searchAuthorView :authorData="authorData" />
    </van-list>
  </div>
  <!-- 搜索结果展示 -->
  <div v-show="travelShow">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      :immediate-check="false"
      offset="100"
      @load="onLoad"
    >
      <card :userTravels="userTravels" />
    </van-list>
  </div>
  <div style="height: 100px"></div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import IMG from "@/icon/found/found-search-back.jpg";
// 防抖函数
import { debounce } from "@/api/debounce.js";
import request from "@/api/request.js";
// 热门城市
import hotCityView from "@/page/search-travel/components/hot-city.vue";
// 搜索的作者
import searchAuthorView from "@/page/search-travel/components/search-author.vue";
// 瀑布流游记
import card from "@/page/Common-components/card-flow.vue";
import { useRouter } from "vue-router";
const $router = useRouter(); // 这是路由跳转的
import emitter from "@/api/event.js";
// 存储搜索历史数据
const historyData = ref([]);
// 存储热门旅游城市
const hotCity = ref([]);
// 存储实时搜索列表
const searchList = ref([]);
// 隐藏 || 显示：搜索历史
const historyShow = ref(true);
// 隐藏 || 显示：搜索列表
const listShow = ref(false);
// 隐藏 || 显示：搜索出来的游记
const travelShow = ref(false);
// 搜索关键词
const keywords = ref("");
// tab选项卡切换
const active = ref(0);
// 存储swiper的宽度
const swiperWidthPx = ref(0);
// 存储有热门城市或没有的样式切换
const styleSwitch = reactive({
  searchBack: false, //顶部搜索栏背景
  categorySearch: false, //是否展示搜索切换选项卡false
  hotCityExist: false, //是否搜索出热门城市
  author: false, //是否展示搜索的作者
});
// 输入时触发
async function seacrhKeyword() {
  console.log("输入时触发");
  historyShow.value = keywords.value == "" ? true : false;
  listShow.value = keywords.value == "" ? false : true;
  travelShow.value = false;
  //是否展示搜索的作者
  styleSwitch.author = false;
  // 请求搜索列表
  const res = await request.get("/search_travel", { keywords: keywords.value });
  searchList.value = res.data;
}
const updateInput = debounce(seacrhKeyword);
// 暂存处理去重的搜索历史
const setKeywords = ref([]);
// 搜索出的游记
const userTravels = ref([]);
// 热门城市轮播
const hotCity_Data = ref([]);
// 热门城市包含的游记
const hotCityTravels = ref([]);
// 存储搜索出的作者数据
const authorData = ref([]);
// 点击搜索列表去搜索数据
async function goSearch(item) {
  keywords.value = item;
  page.value = 1; //再次搜索时要把页数置为1
  finished.value = false;
  pageAuth.value = 1; //再次搜索时要把页数置为1
  finishedAuth.value = false;
  // 判断搜索作者还是游记
  if (tabIndex.value === 0) {
    const res = await request.get("/search_result", { keywords: item });
    // console.log(res);
    hotCity_Data.value = res.data.hotCityData;
    hotCityTravels.value = res.data.hotCityTravels;
    userTravels.value = res.data.userTravels;
    // 如果返回热门城市，就展示轮播的热门城市板块
    styleSwitch.hotCityExist =
      res.data.hotCityTravels.length > 0 ? true : false;
    styleSwitch.searchBack = res.data.hotCityTravels.length > 0 ? true : false;
    travelShow.value = true;
  } else {
    //搜索作者
    const resAuthor = await request.get("/search_author", {
      keywords: item,
      page: 1,
    });
    // console.log(resAuthor);
    styleSwitch.author = true;
    authorData.value = resAuthor.data;
  }
  // 展示搜索选项卡切换
  styleSwitch.categorySearch = true;
  historyShow.value = false;
  listShow.value = false;
  // 存储本地缓存：先去重
  setKeywords.value.unshift(item);
  setKeywords.value = Array.from(new Set(setKeywords.value));
  localStorage.setItem("searchKeywords", JSON.stringify(setKeywords.value));
  // 页面上的搜索历史也要展示
  historyData.value.unshift(item);
  historyData.value = Array.from(new Set(historyData.value));
}
// 进入页面获取本地缓存的搜索历史和热门旅游城市
onMounted(async () => {
  // 获取不同屏幕下swiper的宽度
  const rootFontSize = parseFloat(
    getComputedStyle(document.documentElement).fontSize
  );
  swiperWidthPx.value = 6.6667 * Number(rootFontSize);
  const res = JSON.parse(localStorage.getItem("searchKeywords"));
  historyData.value = res || [];
  const hotcity = await request.get("/hot_city");
  hotCity.value = hotcity.data;
});
// 清空搜索历史
function deleteHistory() {
  historyData.value = [];
  localStorage.removeItem("searchKeywords");
}
// 获取焦点时触发:如果输入框为空，则展示搜索历史部分，否则展示搜索列表
async function focusInput() {
  console.log("获取焦点时触发" + keywords.value);
  historyShow.value = keywords.value == "" ? true : false;
  listShow.value = keywords.value == "" ? false : true;
  travelShow.value = false;
  styleSwitch.hotCityExist = false;
  styleSwitch.categorySearch = false;
  styleSwitch.searchBack = false;
  //是否展示搜索的作者
  styleSwitch.author = false;
  if (keywords.value != "") {
    // 请求搜索列表
    const res = await request.get("/search_travel", {
      keywords: keywords.value,
    });
    searchList.value = res.data;
  }
}
// 手动或回车按下搜索时触发
async function onSearch() {
  await goSearch(keywords.value);
}
// 输入框清空按钮
function clearEvent() {
  historyShow.value = true;
  listShow.value = false;
  travelShow.value = false;
}
// 点击tab选项卡，按游记或用户切换
const tabIndex = ref(0); //存储选项卡选中哪个
async function onClickTab(event) {
  tabIndex.value = event.name;
  await goSearch(keywords.value);
  if (event.name === 0) {
    //游记
    //顶部搜索栏背景
    styleSwitch.hotCityExist = hotCityTravels.value.length > 0 ? true : false;
    //是否搜索出热门城市
    styleSwitch.searchBack = hotCityTravels.value.length > 0 ? true : false;
    // 是否展示游记
    travelShow.value = true;
    //是否展示搜索的作者
    styleSwitch.author = false;
  } else {
    //作者
    //顶部搜索栏背景
    styleSwitch.searchBack = false;
    //是否搜索出热门城市
    styleSwitch.hotCityExist = false;
    // 是否展示游记
    travelShow.value = false;
    //是否展示搜索的作者
    styleSwitch.author = true;
  }
}
// 上啦加载瀑布流游记
const loading = ref(false);
const finished = ref(false);
const page = ref(1);
async function onLoad() {
  page.value++;
  const res = await request.get("/paging_search_result", {
    page: page.value,
    keywords: keywords.value,
  });
  userTravels.value = [...userTravels.value, ...res.data];
  loading.value = false;
  if (res.data.length === 0) {
    finished.value = true;
  }
}
// 上拉加载作者数据
const loadingAuth = ref(false);
const finishedAuth = ref(false);
const pageAuth = ref(1);
async function onLoadAuth() {
  pageAuth.value++;
  const resAuthor = await request.get("/search_author", {
    page: pageAuth.value,
    keywords: keywords.value,
  });
  // console.log(resAuthor);
  authorData.value = [...authorData.value, ...resAuthor.data];
  loadingAuth.value = false;
  if (resAuthor.data.length === 0) {
    finishedAuth.value = true;
  }
}
// 登陆成功被触发重新请求作者数据，
emitter.on("login-success", async () => {
  await goSearch(keywords.value);
});
</script>

<style>
.search-div {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  --van-search-content-background: #f7f8fa !important;
}
/* 有搜索选项卡时 */
.search_height_y {
  height: 98px;
}
/* 没有搜索选项卡时 */
.search_height_n {
  height: 54px;
}
.search-padding {
  padding: 10px;
}
/* 搜索历史和热门城市 */
.search-history {
  margin-bottom: 5px;
}
.search-history img {
  width: 15px;
  height: 15px;
  display: block;
}
.search-history p {
  font-weight: bold;
}
.history-data {
  margin: 10px 0;
}
.history-data p {
  background-color: #f9f9f9;
  border-radius: 40px;
  padding: 6px 10px;
  margin: 0 10px 10px 0;
  font-size: 15px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: calc(7 * 20px + 2 * 0.5px); /* 显示7个字符 */
}
.Hot-city {
  padding: 5px 0;
  box-sizing: border-box;
}
.Hot-city img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  display: block;
  object-fit: cover;
}
.Hot-city div {
  flex: 1;
  padding-left: 10px;
}
.Hot-city p {
  padding: 3px 0;
}
.Hot-city p:nth-child(2) {
  color: #bdbdbd;
}
/* 触发实时搜索展示 */
.search-list {
  padding: 0 10px;
}
.search-list p {
  border-bottom: 1px solid #e3e4e7;
  /* padding: 12px 0; */
  height: 40px;
  line-height: 40px;
}
</style>
